package jike.demo29;

import cn.hutool.core.util.IdUtil;
import jike.demo29.utils.RedisDistributedLock;

import javax.management.InvalidAttributeValueException;
import java.util.concurrent.TimeUnit;

/**
 * @author oyz
 * @version 1.0.4
 * @description: 转账交易类
 * @date 2023/4/15 12:18
 */
public class Transaction {

    private Long id;

    private Long buyerId;

    private Long sellerId;

    private Long orderId;

    private Long productId;

    private Long createTimestamp;

    private Double amount;

    private String status;

    private String walletTransactionId;

    // 添加一个成员变量及其 set 方法
    private WalletRpcService walletRpcService;
    public void setWalletRpcService(WalletRpcService walletRpcService) {
        this.walletRpcService = walletRpcService;
    }

    public Transaction(Long preAssignedId, Long buyerId, Long sellerId, Long productId, Long orderId, Double amount) {
        if (preAssignedId != null) {
            this.id = preAssignedId;
        } else {
            this.id = Long.valueOf(IdUtil.fastUUID());
        }
        this.buyerId = buyerId;
        this.sellerId = sellerId;
        this.productId = productId;
        this.orderId = orderId;
        this.status = STATUS.TO_BE_EXECUTD;
        this.amount = amount;
        // 当前系统时间
        this.createTimestamp = System.currentTimeMillis();
    }

    public boolean execute() throws InvalidAttributeValueException {
        if (buyerId == null || sellerId == null || amount < 0) {
            throw new InvalidAttributeValueException("交易出现错误");
        }
        // 第一次检查
        if (status.equals(STATUS.SUCCESS)) {
            return true;
        }
        boolean isLocked = false;
        try {
            // 锁定当前操作事务
            isLocked = RedisDistributedLock.getSingletonIntance().lockTransction(id);
            if (!isLocked) {
                return false; // 锁定未成功，返回 false，job 兜底执行
            }

            // 第二次检查
            if (status == STATUS.SUCCESS) return true;
            long executionInvokedTimestamp = System.currentTimeMillis();
            if (executionInvokedTimestamp - createTimestamp > TimeUnit.DAYS.toDays(14)) {
                this.status = STATUS.EXPIRED;
                return false;
            }
            // 删除改行
            // WalletRpcService walletRpcService = new WalletRpcService();
            String walletTransactionId = walletRpcService.moveMoney(id, buyerId, sellerId);
            if (walletTransactionId != null) {
                this.walletTransactionId = walletTransactionId;
                this.status = STATUS.SUCCESS;
                return true;
            } else {
                this.status = STATUS.FAILED;
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (isLocked) {
                RedisDistributedLock.getSingletonIntance().unlockTransction(id);
            }
        }
        return isLocked;
    }












}
